package pers.cyw.oraclejavaproject.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnection {
    private DBConnection(){}
    private static Connection connection = null;
    private final static String PROPERTIES_Url = "/jdbc.properties";
    private static String DRIVER_NAME;
    private static String CON_URL;
    private static String USR;
    private static String PSD;
    static {
        Properties properties = new Properties();
        try {
            properties.load(DBConnection.class.getResourceAsStream(PROPERTIES_Url));
            DRIVER_NAME = properties.getProperty("jdbc.driverName");
            CON_URL = properties.getProperty("jdbc.driverUrl");
            USR = properties.getProperty("jdbc.userName");
            PSD = properties.getProperty("jdbc.password");
            Class.forName(DRIVER_NAME);
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        //当connection为空时才建立, 否则说明已建立, 直接返回Connection对象
        if(connection == null){
            System.out.println("建立连接");
            try {
                connection = DriverManager.getConnection(CON_URL,USR,PSD);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
    public static void close(){
        try {
            connection.close();
            connection = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
